package com.binarySearch;

import java.util.Arrays;

public class BinarySearchByMySelf<Item extends Comparable<Item>> {

    private Item[] sortedArray;

    public BinarySearchByMySelf(Item[] sortedArray, boolean alreadySort) {
        this.sortedArray = sortedArray;
        if (!alreadySort) {

            Arrays.sort(this.sortedArray);
        }
    }

    public static int findIndex(int[] anotherSortedArray, int target) {
        int low = 0;
        int high = anotherSortedArray.length - 1;
        int mid = 0;
        while (low <= high) {
            mid = (low + high) / 2;
            int compareResult = target - anotherSortedArray[mid];

            if (compareResult == 0) {
                return mid;
            }
            if (compareResult > 0) {
                low = mid + 1;
                continue;
            }

            if (compareResult < 0) {
                high = mid - 1;
                continue;
            }


        }
        return -1;
    }

    public int findIndex(Item target) {
        int low = 0;
        int high = sortedArray.length;
        int mid = 0;
        while (low < high) {
            mid = (low + high) / 2;
            int compareResult = target.compareTo(sortedArray[mid]);
            if (compareResult > 0) {
                low = mid + 1;
                continue;
            }

            if (compareResult < 0) {
                high = mid - 1;
                continue;
            }

            if (compareResult == 0) {
                return mid;
            }


        }
        return -1;
    }
}
